package com.helloworld.service.impl;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.helloworld.dao.SupplierDao;
import com.helloworld.pojo.Supplier;
import com.helloworld.service.SupplierService;
import com.helloworld.util.PageBean;

@Service
public class SupplierServiceImpl implements SupplierService{
	@Autowired
	private SupplierDao supplierDao;
	
	/**
	 * 分页查询供应商档案
	 */
	@Override
	public PageBean findSupplierByPage(Supplier supplier,int currPage) {
		int pageSize = 10;//每页显示数量
		int begin =(currPage-1)*pageSize;//表示从该条记录开始查询
		int totalCount = findCount(supplier);//总记录数
		
		PageBean pageBean = new PageBean();
		
//		封装当前页码
		pageBean.setCurrPage(currPage);
//		封装每页显示数量
		pageBean.setPageSize(pageSize);
//		封装总记录数
		pageBean.setTotalCount(totalCount);
//		封装总页数
        double tc = totalCount;
        Double num =Math.ceil(tc/pageSize);//向上取整
        pageBean.setTotalPage(num.intValue());
        
        DetachedCriteria criteria = DetachedCriteria.forClass(Supplier.class);
		if (supplier != null) {
			if (supplier.getSupplierName() != null &&! supplier.getSupplierName().isEmpty()) {
				criteria.add(Restrictions.like("supplierName","%"+supplier.getSupplierName()+"%"));
			}
			if (supplier.getLinkman() != null &&! supplier.getLinkman().isEmpty()) {
				criteria.add(Restrictions.like("linkman","%"+supplier.getLinkman()+"%"));
			}
			if (supplier.getSupplierMobile() != null &&! supplier.getSupplierMobile().isEmpty()) {
				criteria.add(Restrictions.like("supplierMobile","%"+supplier.getSupplierMobile()+"%"));
			}
			List<Supplier> list = supplierDao.findSupplierByPage(criteria, begin,pageSize);
			
//			封装每页显示的内容
			pageBean.setList(list);
			return pageBean;
		}
		List<Supplier> list = supplierDao.findSupplierByPage(criteria, begin, pageSize);
		pageBean.setList(list);
		return pageBean;
	}
	
	
	/**
	 * 查询总记录数
	 * @param supplier
	 * @return
	 */
	public int findCount(Supplier supplier) {
		String hql="select count(*) from Supplier where 1=1";
//		判断是否是条件查询
		if (supplier != null) {
			if (supplier.getSupplierName() != null && supplier.getSupplierName() != "") {
				hql += " and supplier_name like '%"+supplier.getSupplierName()+"%'";
			}
			if (supplier.getLinkman() != null && supplier.getLinkman() != "") {
				hql +=" and linkman like '%"+supplier.getLinkman()+"%'";
			}
			if (supplier.getSupplierMobile() != null && supplier.getSupplierMobile() != "") {
				hql += " and supplier_mobile like '%" + supplier.getSupplierMobile()+"%'";
			}
		}
		
		List<Long> list = supplierDao.findCount(hql);
		if(list.size()>0){
            return list.get(0).intValue();
        }
        return 0;
		
	}

}
